package cn.enjoy.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author K
 * @date 2022-07-20 22:25
 */
@Configuration
public class MqQueueDLXConfig {


    /**
     * DLX死信交换机
     */
    @Bean("DLXExchange")
    public DirectExchange DLXExchange() {
        return new DirectExchange("DLXExchange", true, false);
    }

    @Bean("DLXQueue")
    public Queue DLXQueue() {
        return new Queue("DLX_QUEUE", true, false, false);
    }

    @Bean
    public Binding deadBinding(@Qualifier("DLXExchange") DirectExchange exchange, @Qualifier("DLXQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(exchange).with("dlx.k");
    }

    /**
     * 正常交换机
     */
    @Bean("normalExchange")
    public TopicExchange normalExchange() {
        return new TopicExchange("NORMAL_EXCHANGE", true, false);
    }

    @Bean("normalQueue")
    public Queue normalQueue() {
        HashMap<String, Object> map = new HashMap<>();
        // 3 秒钟后成为死信
        map.put("x-message-ttl", 3000);
        // 绑定死信交换机，队列中的消息变成死信后，进入死信交换机
        map.put("x-dead-letter-exchange", "DLXExchange");
        // 通过dlx.hello路由到交换机
        map.put("x-dead-letter-routing-key", "dlx.k");
        return new Queue("NORMAL_QUEUE", true, false, false, map);
    }

    @Bean
    public Binding normalBinding(@Qualifier("normalExchange") TopicExchange topicExchange, @Qualifier("normalQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(topicExchange).with("normal.dlx.#");
    }

}
